<template>

  <ul v-for="(item, index) in cartList">
    {{item.imgurl}}
    {{item.price}}
    {{item.skuCount}}
    <el-button @click="handleAddCart(item)">+</el-button>
    <el-button >{{item.skuCount}}</el-button>
    <el-button @click="handleRemoveCart(item)">-</el-button>
    <hr>
  </ul>

</template>

<script>
import { reactive, toRefs, onMounted } from 'vue'
import ajax from '@/utils/request.js'

// 请求数据逻辑
const useEffectGetCartList = async () => {
  const data = await ajax.get('/api/findCartList')
  return { data: data.data }
}

// 数据+
const useEffectAddItem = async (item) => {
  const data = await ajax.post('/api/updateSkuount', {
    skuCount: item.skuCount+1,
    skuId: item.skuId
  })
}

// 处理删除购物车列表接口
const useEffectDeleteItem = async (item) => {
  const result = await ajax.delete(`/api/deleteCartItem/${item.skuId}`)
}

const useEffectRemoveItem = async (item) => {
  if (item.skuCount <=1) {
    return {flag: true}
  }
 const data = await ajax.post('/api/updateSkuount', {
    skuCount: item.skuCount-1,
    skuId: item.skuId
  })
}

export default {
  setup(props) {
    const state = reactive({
      cartList: []
    })

    useEffectGetCartList().then(res => {
      state.cartList = res.data;
    })

    // // 数据加+
    const handleAddCart = async (item) => {
      useEffectAddItem(item)
      useEffectGetCartList()
    }
    // 数据-
    const handleRemoveCart = async (item) => {
      const { flag } = useEffectRemoveItem(item)
      if (flag) {
        useEffectDeleteItem(item)
      }
      useEffectGetCartList()
    }
    const { cartList } = toRefs(state);

    return {
       cartList,
       handleAddCart,
       handleRemoveCart
    }
  }
}
</script>